package org.saxion.saktiehuis;

import org.saxion.saktiehuis.model.UserSession;
import org.saxion.saktiehuis.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController {
	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);

	@Autowired
	UserService userService;
	@Autowired
	UserSession session;

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(Model model) {
		logger.info("Gebruiker is uitgelogd");
		session.logout();
		return "redirect:/";
	}

	@RequestMapping(value = "/login")
	public String login(Model model) {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginAction(@RequestParam("username") String username,
			@RequestParam("password") String password, Model model) {
		if (!username.equals("") && !password.equals("")
				&& userService.login(username, password)) {
			logger.info("Gebruiker " + username + " is ingelogd");
			session.login(username);
			return "redirect:/";
		} else {
			logger.info("Foute login = username: [" + username
					+ "] / password: [" + password + "]");
			model.addAttribute("error", true);
			return "login";
		}
	}

	@RequestMapping(value = "/register")
	public String register(Model model) {
		return "register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String registerAction(@RequestParam("username") String username,
			@RequestParam("password1") String password1,
			@RequestParam("password2") String password2, Model model) {
		if (!username.equals("") && !password1.equals("")
				&& !password2.equals("") && password1.equals(password2)
				&& userService.register(username, password1)) {
			logger.info("Gebruiker " + username + " is geregistreerd");
			session.login(username);
			return "redirect:/";
		} else {
			logger.info("Foute registratie= username: [" + username
					+ "] / password1: [" + password1 + "] / password2: ["
					+ password2 + "]");
			model.addAttribute("error", true);
			return "register";
		}
	}
}
